<!-- V-webapp/src/views/LoginView.vue -->
<template>
  <div class="login-page">
    <div class="login-container">
      <!-- 头部 -->
      <div class="login-header">
        <h1>虚拟社区平台</h1>
        <p>连接创作者与粉丝的虚拟社区</p>
      </div>

      <!-- 登录表单 -->
      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入账号"
            size="large"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            @click="handleLogin"
            :loading="loading"
            class="login-btn"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 账号类型提示 -->
      <div class="account-tips">
        <el-divider>账号类型说明</el-divider>
        <div class="tip-item">
          <el-icon><User /></el-icon>
          <span>粉丝账号：普通用户名或邮箱格式</span>
        </div>
        <div class="tip-item">
          <el-icon><Monitor /></el-icon>
          <span>主播账号：T.七月、T.赵太阳、T.测试等</span>
        </div>
        <div class="tip-item">
          <el-icon><InfoFilled /></el-icon>
          <span>系统会根据账号类型自动跳转到对应平台</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Monitor, InfoFilled } from '@element-plus/icons-vue'
import { login } from '@/api/auth'

const router = useRouter()
const route = useRoute()
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const loginFormRef = ref()

// 识别特定的 T. 主播账号
const isSpecificTAnchor = (username: string) => {
  const specificTAnchors = [
    'T.测试',
    'T.七月', 
    'T.赵太阳',
    'T.银河',
    'T.樱花酱',
    'T.炎龙'
  ]
  
  return specificTAnchors.includes(username)
}

// 处理登录 - 智能跳转逻辑
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    console.log('🔐 开始登录...', loginForm.username)

    // 调用登录API
    const response = await login(loginForm)
    console.log('✅ 登录响应:', response)
    
    // 修复：正确获取Token和用户信息
    if (response.success || response.code === 200) {
      const token = response.data.token
      const userInfo = response.data.user
      const accountTypeFromAPI = response.data.accountType // 使用API返回的账号类型
      
      console.log('🔐 获取到Token:', token ? `长度:${token.length}` : '不存在')
      console.log('👤 获取到用户信息:', userInfo)
      console.log('🎯 API返回账号类型:', accountTypeFromAPI)
      
      if (!token) {
        throw new Error('登录失败：未获取到Token')
      }
      
      // 保存token和用户信息 - 添加详细验证
      console.log('💾 开始保存用户信息到localStorage...')
      
      localStorage.setItem('token', token)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      localStorage.setItem('userType', accountTypeFromAPI)
      
      // 立即验证保存是否成功
      console.log('🔍 验证保存结果:')
      const savedToken = localStorage.getItem('token')
      const savedUserType = localStorage.getItem('userType')
      const savedUserInfo = localStorage.getItem('userInfo')
      
      console.log('   Token保存:', savedToken ? `成功 (${savedToken.substring(0, 20)}...)` : '失败')
      console.log('   UserType保存:', savedUserType ? `成功 (${savedUserType})` : '失败')
      console.log('   UserInfo保存:', savedUserInfo ? '成功' : '失败')
      
      if (!savedToken || !savedUserType) {
        throw new Error('用户信息保存失败，请重试')
      }
      
      console.log('✅ 所有用户信息保存成功')
      
      ElMessage.success('登录成功')
      
      // 根据账号类型和来源页面决定跳转
      const redirectPath = route.query.redirect as string
      
      console.log('🔄 跳转判断:', { 
        username: loginForm.username, 
        userType: savedUserType,
        redirectPath 
      })
      
      // 判断是否为特定的 T. 主播账号
      const isTAnchor = isSpecificTAnchor(loginForm.username)
      
      if (isTAnchor) {
        // 特定的 T. 主播账号 → 管理后台
        if (isMobileDevice() && !redirectPath?.includes('/admin')) {
          // 在手机上登录主播账号，提示在电脑上登录
          ElMessage.warning('主播账号请在电脑端登录管理后台')
          // 仍然跳转到粉丝端首页
          router.push(redirectPath || '/')
          return
        }
        
        // 跳转到管理后台 - 通过URL参数传递token
        const adminBaseURL = 'http://localhost:5175'
        // 直接跳转到根路径，让路由自动重定向到dashboard
        let adminRedirectPath = '/'
        
        if (redirectPath) {
          // 解析redirect参数，提取路径部分
          try {
            const url = new URL(redirectPath)
            adminRedirectPath = url.pathname + url.search
          } catch {
            // 如果不是完整URL，直接使用
            adminRedirectPath = redirectPath
          }
        }
        
        // 构建带token的URL参数
        const params = new URLSearchParams()
        if (savedToken) params.append('token', savedToken)
        if (savedUserType) params.append('userType', savedUserType)
        if (savedUserInfo) params.append('userInfo', savedUserInfo)
        
        const queryString = params.toString()
        const finalURL = `${adminBaseURL}${adminRedirectPath}${queryString ? '?' + queryString : ''}`
        
        console.log('🚀 跳转到管理后台 (带参数):', finalURL)
        
        // 添加跳转前的最后验证
        console.log('🔍 跳转前最终验证:')
        console.log('   Token:', localStorage.getItem('token') ? '存在' : '不存在')
        console.log('   UserType:', localStorage.getItem('userType'))
        
        window.location.href = finalURL
      } else {
        // 粉丝账号或其他账号 - 直接跳转，不检查设备类型
        console.log('🏠 跳转到粉丝端首页')
        router.push(redirectPath || '/')
      }
    } else {
      throw new Error(response.message || '登录失败')
    }

  } catch (error: any) {
    console.error('❌ 登录错误:', error)
    ElMessage.error(error.response?.data?.message || error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 检测设备类型
const isMobileDevice = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  background: white;
  border-radius: 12px;
  padding: 40px;
  width: 100%;
  max-width: 400px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  color: #333;
  margin-bottom: 8px;
  font-size: 24px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}

.account-tips {
  margin-top: 20px;
}

.tip-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.tip-item .el-icon {
  margin-right: 8px;
  color: #409eff;
}
</style>